﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text.RegularExpressions;
using ZX.BLL.Extend;
using System.Text;
using System.Collections;
using ZX.SYS.Library;

namespace ZX.Web.UI.Controls
{
    public partial class DesktopMain : BasePage
    {
        string[] _colors = { "bg_lb", "bg_db", "bg_lg", "bg_ly", "bg_dy", "bg_lb", "bg_ls", "bg_lo", "bg_lr", "bg_lv" };

        public string _ShortcutItem = "";
        public StringBuilder _Custom_clum_left = new StringBuilder( "");
        public StringBuilder _Custom_clum_right = new StringBuilder( "");
        protected void Page_Load(object sender, EventArgs e)
        {
           CreateShortcutItem();
           //CreateDesktopItem();
        }


        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        void CreateShortcutItem()
        {
            ZX.BLL.Extend.BaseBussnies bll = new BaseBussnies();
            bll.Order = "Sort";
            bll.Desc = "Yes";
            IList<UserShortcut> list = bll.GetEntitys<UserShortcut>(string.Format("AddUser='{0}'", this.UserId));
            StringBuilder strTemplate = new StringBuilder("");
            if (list != null)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    string _strTemplate = "";
                    _strTemplate = _strTemplate + "<li class=\"" + _colors[i % 10] + "\">";
                    _strTemplate = _strTemplate + "<a href=\"#\" url=\"" + list[i].URL + "&functionid=" + list[i].FunctionID + "\"><i class=\"icon-tablet\"></i>" + list[i].Name + "</a></li>";
                    strTemplate.Append(_strTemplate);
                }
            }
            _ShortcutItem =  strTemplate.ToString();
        }

        void CreateDesktopItem()
        {
            IList<DesktopItem> list = LoadData();
            foreach (var e in list)
            {
                fnBuildItem(e);
            }
        }


        IList<DesktopItem> LoadData()
        {
            string strsql = @"SELECT DISTINCT CASE WHEN sud1.AddUser IS NULL 
	                            THEN 1 
	                            ELSE (CASE WHEN sud.UserDesktopID IS NULL THEN 0 ELSE 1 END)
	                            END AS IsChecked
                                ,sdt.Region
                                ,sud.AddUser
                                        ,srd.[DeskTopTempID]
                                        ,sdt.DeskTopTempName AS [name]
                                        ,sdt.[Height]
                                        ,MIN(ISNULL(sud.Sort,srd.[Sort])) OVER(PARTITION BY srd.[DeskTopTempID]) AS Sort
                                        ,sdt.[src]
                                        ,sdt.pageType
                                        ,MIN(Coalesce(srd.PowerType,sdt.PowerType,0)) OVER (PARTITION  BY sdt.DeskTopTempID) AS powerType
                                        ,sdt.[TabTools] as tools
                                        ,sdt.more
                                FROM SysRoleDesktop srd
		                            INNER JOIN SysDesktopTemplate sdt ON srd.DeskTopTempID=sdt.DeskTopTempID
		                            INNER JOIN SysUserRole sur ON srd.RoleID=sur.RoleID
		                            LEFT JOIN SysUserDesktop sud ON srd.DeskTopTempID=sud.RoleDesktopID AND sur.UserID=sud.AddUser
		                            LEFT JOIN SysUserDesktop sud1 ON sud1.AddUser='{0}'
                                WHERE sur.UserID='{0}'
                                ORDER BY IsChecked desc,Sort asc";
            strsql = string.Format(strsql, this.UserId);
            ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies();
            IList<DesktopItem> list = bll.GetEntitysBySqlComm<DesktopItem>(strsql);
            return list;
        }

        /// <summary>
        /// 获取数据内容
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        string GetPageData(string url)
        {
            WebClient MyWebClient = new WebClient();
            MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于对向Internet资源的请求进行身份验证的网络凭据。       
            string data = "";
            try
            {
                url = this.GetCurrentHostPort + url.Replace("..", "Desktop/");
                Byte[] pageData = MyWebClient.DownloadData(url);
                data = System.Text.Encoding.UTF8.GetString(pageData);
                if (data == "[]")
                {
                    return null;
                }
            }
            catch (Exception e)
            {
                return "";
            }
            return data;
        }



        int __i = 0;
        string _tabtemplate_title = "<div class=\"widget-title\">" +
                    "<ul class=\"nav nav-tabs\">" +
                        "[nav]" +
                    "</ul>" +
                "</div>";
        string _tabtemplate_content = "<div class=\"widget-content tab-content nopadding collapse in\">[content]</div>";
        string _template = "<div class=\"widget-box\">" +
          "<div class=\"widget-title bg_ly\" data-toggle=\"collapse\" href=\"#[i]\"><span class=\"icon\"><i class=\"icon-chevron-down\"></i></span>" +
          "<h5>[title]</h5>" +
          "</div>" +
          "<div class=\"widget-content nopadding collapse in\" id=\"[id]\">" +
           "<div>[content]</div>" +
            "<ul class=\"recent-posts\">" +
            "<li>" +
                "<button class=\"btn btn-warning btn-mini\">View All</button>" +
              "</li>" +
            "</ul>" +
          "</div>" +
        "</div>";
        /// <summary>
        /// 
        /// </summary>
        /// <param name="o"></param>
        void fnBuildItem(DesktopItem o)
        {
            if (o == null)
            {
                return;
            }

            //__i = __i + 1;
            if (o.tools != "" && o.tools != null)
            {
                string _tabLiHtml = "";
                string _tabContentHtml = "";

                string text = o.tools;
                string pat = @"(TabUrl=""[^<]*"")";
                string pat2 = @"(TabPro=""[^<]*"")";
                // Compile the regular expression.
                Regex r = new Regex(pat, RegexOptions.IgnoreCase);
                Regex r2 = new Regex(pat2, RegexOptions.IgnoreCase);
                // Match the regular expression pattern against a text string.
                Match m = r.Match(text);
                Match m2 = r2.Match(text);
                IList<string> _url = new List<string>();
                IList<string> _url2 = new List<string>();
                while (m.Success)
                {
                    //Response.Write("Match" + (++matchCount) + "<br>");
                    for (int i = 0; i <= m.Groups.Count; i++)
                    {
                        Group g = m.Groups[i];
                        if (g.Value == "")
                        {
                            continue;
                        }
                        string str = g.Value.Split(' ')[0].Remove(0, "TabUrl=\"".Length).Replace("\"", "");
                        _url.Add(str);
                    }
                    m = m.NextMatch();
                }

                while (m2.Success)
                {
                    //Response.Write("Match" + (++matchCount) + "<br>");
                    for (int i = 0; i <= m2.Groups.Count; i++)
                    {
                        Group g = m2.Groups[i];
                        if (g.Value == "")
                        {
                            continue;
                        }
                        string str = g.Value.Remove(0, "TabUrl=\"".Length).Replace("\"", "");
                        _url2.Add(str);
                    }
                    m2 = m2.NextMatch();
                }

                for (int i = 0; i < _url.Count; i++)
                {
                    string __url = _url[i] + "?" + _url2[i];
                    string __tabId = o.id + '_' + i;
                    string __li = ("<li class=\"active\"><a data-toggle=\"tab\" href=\"#" + __tabId + "\">" + __tabId + "</a></li>").Replace("active", (i != 0 ? "" : "active"));

                    _tabLiHtml += __li;
                    string _datatemp = "";
                    if (o.pageType == "1")
                    {
                        _datatemp = "<iframe scrolling=\"auto\" frameborder=\"0\"  src=\"" + __url + "\" style=\"width:100%;height:100%; margin:0px;\"></iframe>";
                    }
                    else
                    {
                        _datatemp = GetPageData(__url);
                    }
                    _tabContentHtml += ("<div id=\"" + __tabId + "\" class=\"tab-pane active nopadding\">" + _datatemp + "</div>").Replace("active", (i != 0 ? "" : "active"));
                }
                string __tabtemplate_title = _tabtemplate_title.Replace("[nav]", _tabLiHtml);
                string __tabtemplate_content = _tabtemplate_content.Replace("[content]", _tabContentHtml);
                string  html = "<div class=\"widget-box\">" + __tabtemplate_title + __tabtemplate_content + "</div>";
                if (o.Region == "right") {
                  this._Custom_clum_right.Append(html);
                }
               else {
                   this._Custom_clum_left.Append(html);
               }
            }
            else
            {
                string _datatemp = "";
                if (o.pageType == "1")
                {
                    _datatemp = "<iframe scrolling=\"auto\" frameborder=\"0\"  src=\"" + o.src + "\" style=\"width:100%;height:100%; margin:0px;\"></iframe>";
                }
                else
                {
                    _datatemp = GetPageData(o.src);
                }
                //var _datatemp = getUrlData(e.src);
                var html = _template.Replace("[title]", o.title).Replace("[content]", _datatemp);
                if (o.Region == "right")
                {
                    _Custom_clum_right.Append(html); ;
                }
                else
                {
                    _Custom_clum_right.Append(html);
                }
            }
        }
    }
}   

